#!/usr/bin/env python3

from serial import Serial
from serial.tools.list_ports import comports

class Programmer(Serial):
    def __init__(self):
        # super().__init__(baudrate=1000000, timeout=2, write_timeout=2)
        super().__init__(baudrate = 115200, timeout = 3, write_timeout = 2)
        # self.identify()

    def testConnect(self,comport):
        pid = '1A86'
        hid = '7523'
        did = 'EEPROM28NEW'
        # did = 'EEPROM Programmer'
        for p in comports():
            if p.device == comport:
                if pid and hid in p.hwid:
                    print("使用ch340连接")
                else:
                    print("使用非ch340连接")
                # 设置驱动设备 COMX
                self.port = p.device
                try:
                    self.open()
                except:
                    continue
                try:
                    if self.is_open:
                        if self.confirmation():
                            self.sendcommand('i')
                            data = self.getline()
                            print('data1:{}'.format(data))
                        else:
                            print("Not ready")
                            return -1
                    else:
                        print('Port not open')
                        return -1
                except:
                    self.close()
                    return -1

                if data == did:
                    data = self.readline()
                    print("did:{}".format(data))
                    # 正常返回
                    return 1
                else:
                    self.close()
                    # 版本不匹配
                    return -9999
            else:
                print("没有找到 {}".format(comport))
        return -9

    def connect(self,comport):
        for p in comports():
            if p.device == comport:
                self.port = p.device
                try:
                    self.open()
                    if self.is_open:
                        if self.confirmation():
                            return True
                except:
                    continue
        return False

    def sendcommand(self, cmd, chip='', startAddr=-1, endAddr=-1):
        cmd += ' %6s' % chip
        if startAddr >= 0:
            cmd += '  %04x' % startAddr
            if endAddr >= 0:
                cmd += '  %04x' % endAddr
        self.write((cmd + '\n').encode())
        print("输出命令:{}".format(cmd))


    def getline(self):
        return self.readline().decode().rstrip('\r\n')


    def confirmation(self):
        return (self.getline() == 'Ready')


    def getversion(self):
        self.sendcommand ('v')
        version = self.getline()
        self.readline()
        return version


    def unlock(self):
        self.sendcommand('u')
        return self.confirmation()


    def lock(self):
        self.sendcommand('l')
        return self.confirmation()


if __name__ == '__main__':
    eeprom = Programmer()
    eeprom.connect("COM3")
    if not eeprom.is_open:
        print('ERROR: EEPROM Programmer not found')
        exit(1)

    print('EEPROM Programmer found on ' + eeprom.port)
    print('Firmware version: ' + eeprom.getversion())
